package com.googlecode.allinclusive.fw.dict;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.googlecode.allinclusive.fw.database.ibatis.EntityManager;

public class DictLoaderIBatisImpl implements DictLoader {
	
	private static final Log log = LogFactory.getLog(DictLoaderIBatisImpl.class);
	
	@Autowired
	private EntityManager entityManager;
	
	/**
	 * 加载数据字典信息
	 * @return 数据字典信息
	 */
	@Override
	public synchronized Map<String, List<DictValue>> load() {
		if (log.isDebugEnabled()) {
			log.debug("dict initializing.");
		}

		Map<String, List<DictValue>> cacheMap = new ConcurrentHashMap<String, List<DictValue>>();
		// SQL执行
		List<DictValue> dictValues = entityManager.executeForObjectList("dict.select", null);
		if (dictValues == null || dictValues.isEmpty()) {
			return cacheMap;
		}

		for (DictValue dictValue : dictValues) {
			List<DictValue> dictValueList = cacheMap.get(dictValue.getDictTypeCode());
			if (dictValueList == null) {
				dictValueList = new ArrayList<DictValue>();
				cacheMap.put(dictValue.getDictTypeCode(), dictValueList);
			}
			dictValueList.add(dictValue);
		}
		
		return cacheMap;
	}

}
